# -*- coding: utf-8 -*-
import base64
import hashlib
import hmac
import json
from collections import OrderedDict

import requests
from django.conf import settings
from django.template import Context
from django.template.loader import get_template

from async import async_job
from common.cache import redis_cache
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.qr import make_code

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    'caesar': {  # 扫码 2.5% 300～3000 witch
        'API_KEY': 'yWx2Zpt186PyoZhW2gxXjwXacZf4Df3kS6r5XGE7pfCJ8JtzIGsbON3G5DwJ',
        'gateway': 'https://onegopay.com/api/transaction',
        'query_gateway': 'https://onegopay.com/api/transaction/{}',
    },
    'caesar02': {  # H5 2.5% 300～3000 witch
        'API_KEY': '1HIAMQYmVUQHYhABjbZsYDopvVSIGUzOzXkiYnSkz4Un4HezPsyJn2e3hLgC',
        'gateway': 'https://onegopay.com/api/transaction',
        'query_gateway': 'https://onegopay.com/api/transaction/{}',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _gen_sha256_sign(key, s):
    return base64.b64encode(hmac.new(key.encode("utf-8"), s.encode("utf-8"), hashlib.sha256).digest())


def verify_notify_sign(sign, body, key):
    calculated_sign = _gen_sha256_sign(key, body)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("onegopay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % body)


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    parameter_dict = OrderedDict((
        ('amount', str(pay_amount)),
        ('out_trade_no', str(pay.id)),
        ('notify_url', '{}/pay/api/{}/onegopay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
    ))
    headers = {'Content-Type': 'application/json;charset=utf-8', 'Authorization': 'Bearer ' + _get_api_key(app_id)}
    _LOGGER.info('onegopay create data, %s, headers: %s', json.dumps(parameter_dict), headers)
    response = requests.post(_get_gateway(app_id), json=parameter_dict, headers=headers, timeout=3, verify=False)
    _LOGGER.info('onegopay create rsp, %s', response.text)
    if service == 'alipay_h5':
        return {'charge_info': json.loads(response.text)['uri']}
    elif service == 'alipay_scan':
        data = json.loads(response.text)
        template_data = {'base64_img': make_code(data['uri']), 'amount': pay_amount}
        t = get_template('qr_alipay_onegopay.html')
        html = t.render(Context(template_data))
        cache_id = redis_cache.save_html(pay.id, html)
        _LOGGER.info("onegopay create_url: %s, pay.id: %s", settings.PAY_CACHE_URL + cache_id, pay.id)
        return {'charge_info': settings.PAY_CACHE_URL + cache_id}
    else:
        return {'charge_info': ''}


# 888888
def check_notify_sign(request, app_id):
    sign = request.META.get('HTTP_X_GOPAY_SIGNATURE', 0)
    api_key = _get_api_key(app_id)
    data = json.loads(request.body)
    _LOGGER.info("onegopay notify data: %s, order_id is: %s", data, data['out_trade_no'])
    verify_notify_sign(sign, request.body, api_key)
    pay_id = data['out_trade_no']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s", data)
        raise ParamError('onegopay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['status'])
    trade_no = data['trade_no']
    total_fee = float(data['amount'])
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    check_channel_order(pay_id, total_fee, app_id)
    # 狀態碼 success => 成功  progress => 進行中  timeout => 逾時
    if trade_status == 'success':
        _LOGGER.info('onegopay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    pay_id = pay_order.id
    headers = {'Content-Type': 'application/json;charset=utf-8', 'Authorization': 'Bearer ' + _get_api_key(app_id)}
    url = _get_query_gateway(app_id).format(pay_order.third_id)
    response = requests.get(url, headers=headers)
    _LOGGER.info('onegopay query rsp data: %s, order_id is: %s', response.text,
                 json.loads(response.text)['out_trade_no'])
    if response.status_code == 200:
        data = json.loads(response.text)
        mch_id = pay_order.mch_id
        trade_status = str(data['status'])
        total_fee = float(data['amount'])
        trade_no = pay_order.third_id
        extend = {
            'trade_status': trade_status,
            'total_fee': total_fee,
            'trade_no': trade_no,
        }
        # 狀態碼 success => 成功  progress => 進行中  timeout => 逾時
        if trade_status == 'success':
            check_channel_order(pay_id, total_fee, app_id)

            _LOGGER.info('onegopay query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)

            async_job.notify_mch(pay_order.id)
